import "reflect-metadata";
import {Autowired, Singleton, get, post, Controller} from '../decorator'
import {UserServiceInter, UserServiceImpl} from "../service";
import { Request, Response } from 'express'
import { getSession } from '../util/SessionUtil';
import UserInfo from "../entity/UserInfo";

// 装饰器执行顺序：1.属性装饰器==>2.方法参数装饰器==>3.方法装饰器==>4.构造函数参数装饰器==>5.类装饰器
@Controller("/user")
class UserController {

    @Autowired("userServiceImpl")
    @Singleton(true)
    private userServiceImpl!: UserServiceInter

    @get("/login")
    public login(req: Request, res: Response): void {
        let htmlstr = `<div><form method="post" action = "/user/loginprocess">
                          <div>用户名: <input type='text' name = 'username'/></div>
                          <div>密码: <input type='password' name = 'pwd'/></div>
                          <div><input type="submit" value = "提交" /> </div>
                        </form></div>`
        res.send(htmlstr);
    }

    @post("/loginprocess")
    loginProcess(req: Request, res: Response): void {
        console.log("loginprocess=this:", this);
        let session = getSession(req);

        let userServiceImpl: UserServiceImpl = Reflect.getOwnPropertyDescriptor(UserController.prototype, "userServiceImpl").value//S100
        let userInfo: UserInfo = userServiceImpl.login(req.body.username, req.body.pwd);
        //将userInfo放入session中保存
        if (userInfo && userInfo.username){
            session.userInfo = userInfo
        }
        // 基础复习：req.send只能发送一次,如果想发送多次,就必须使用res.write
        res.setHeader("Content-Type", "text/html;charset=UTF-8")
        let outputhtml = "";
        if (userInfo.role === "admin") {
            outputhtml += `<div>管理员:${userInfo.role}</div>`
            outputhtml += `<div><a href="/rights/rightsmanager">进入管理员权限页面</a></div>`
        }
        res.write(outputhtml);
        res.write(`<div>登录成功,欢迎你:${userInfo.username}</div>`);
        res.write(`<div><a  href="/">进入首页</a></div>`);
        res.write(`<div><a  href="/food/showfood">进入美食首页</a></div>`);
        res.end();
    }

    public register(): void {
        let userService = Reflect.getOwnPropertyDescriptor(UserController.prototype, "userServiceImpl")!.value;
        let result = userService.register("admin", "123");
        if (result) {
            console.log("注册成功!");
        } else {
            console.log("注册失败!");
        }
    }
}
